package main

import (
	"fmt"
	"net"
	"os"
	"strconv"
	"strings"
	"time"
)

func main() {
	service := "127.0.0.1:5002"
	if len(os.Args) == 2 {
		service = os.Args[1]
	}

	//输入三元组（ip,协议，端口） 返回socket
	tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
	checkError(err)

	//进行端口监听
	listener, err := net.ListenTCP("tcp", tcpAddr)
	checkError(err)
	for {
		//接受连接
		conn, err := listener.Accept()
		if err != nil {
			continue
		}
		go handleClient(conn)
	}
}

//处理客户端请求
func handleClient(conn net.Conn) {
	//conn.SetReadDeadline(time.Now().Add(10 * time.Second))
	request := make([]byte, 128)

	//defer conn.Close()

	for {
		real_len, err := conn.Read(request)
		if err != nil {
			fmt.Println(err)
			break
		}

		if real_len == 0 {
			break
		} else if strings.TrimSpace(string(request[:real_len])) == "timestamp" {
			daytime := strconv.FormatInt(time.Now().Unix(), 10)
			conn.Write([]byte(daytime))

		} else {
			daytime := time.Now().String()
			fmt.Println(daytime)
			conn.Write([]byte(daytime))
		}

		request = make([]byte, 128)

	}
}

func checkError(err error) {
	if err != nil {
		fmt.Fprintf(os.Stderr, "Fatal error:%s", err.Error())
		os.Exit(1)
	}

}
